#include <iostream>
#include <sstream>
using namespace std;

#include "expression.h"

void Expression::selfFromString(const string s)
{
	for(string::const_iterator i = s.begin(); i != s.end(); ++i)
	{
		if(isdigit(*i) || *i == '.')
		{
			stringstream num;
			while(i != s.end() && (isdigit(*i) || *i == '.'))
			{
				num << *i;
				++i;				
			}
			--i;
			float f;
			num >> f;
			append(new Number(f));
		}
		else if(strchr("+=*/^", *i))
		{
			if(value)
			{
				Expression* binExp = new BinaryExpression(*i);
				int a = value->getImportance();
				int b = binExp->getImportance();
				if(value->getImportance() > binExp->getImportance())
				{
					binExp->append(value);
					value = binExp;
				}
				else
				{
					value->append(binExp);
				}				
			}
			else
			{
				cout << "Trying to operate on nothing." << endl;
				system("pause");
				exit(1);
			}
		}
		else if(*i == '(')
		{
			string inner;
			int p = 1;
			while(i != s.end() && p)
			{
				++i;
				if(*i == '(')
					++p;
				else if(*i == ')')
					--p;
				if(p)
					inner += *i;
			}
			append(new Expression(inner));
		}
	}
}

string Expression::BinaryExpression::toString(void) const
{
	stringstream s;
	if(left && right)
	{
		int a = left->getImportance();
		int b = right->getImportance();
		int c = getImportance();
		if( left->getImportance() != 1 && left->getImportance() < getImportance() )
			s << '(' << left->toString() << ')';
		else
			s << left->toString();

		s << op;

		if( right->getImportance() != 1 && right->getImportance() < getImportance() )
			s << '(' << right->toString() << ')';
		else
			s << right->toString();
		//s << '(' << left->toString() << op << right->toString() << ')';
		return s.str();
	}
	else
		return "[Incomplete binary expression]";
}